package com.jinzhi.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.msg.PackTemplateMap;
import com.jinzhi.jzapi.msg.WxPushServiceQcl;
import com.jinzhi.jzapi.msg.domain.TemplateData;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.ExpertsService;
import com.jinzhi.jzweb.service.MsgService;
import com.jinzhi.jzweb.service.MsgTemplateService;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.SysUserRelevancyService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.sys.vo.UserVO;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <pre>
 * </pre>
 * <p>
 * <small> 2018年3月23日 | Aron</small>
 */
@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
    private String prefix = "sys/user";
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    SysUserRelevancyService userRelevancyService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    DictService dictService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private MsgTemplateService msgTemplateService;
    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;
    @Autowired
    private MpConfigService mpConfigService;

    @Log("进入系统用户列表页面")
    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }

    @Log("查询系统用户列表")
    @GetMapping("/list")
    @ResponseBody
    public Result<Page<UserDO>> list(UserDO userDTO) {
        Wrapper<UserDO> wrapper = new EntityWrapper<UserDO>().orderBy("id", false);
        if (userDTO.getSex() != null) {
            wrapper.eq("sex", userDTO.getSex());
        }
        if (userDTO.getStatus() != null) {
            wrapper.eq("status", userDTO.getStatus());
        }
        if (userDTO.getType() != null) {
            wrapper.eq("type", userDTO.getType());
        }
        if (userDTO.getName() != null) {
            wrapper.like("name", userDTO.getName());
        }
        if (userDTO.getUsername() != null) {
            wrapper.like("username", userDTO.getUsername());
        }
        if (userDTO.getMobile() != null) {
            wrapper.like("mobile", userDTO.getMobile());
        }
        if (userDTO.getState() != null){
            wrapper.eq("state" , userDTO.getState());
        }
        if (StringUtils.isNotBlank(userDTO.getOrgName())) {
            Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name", userDTO.getOrgName());
            List<OrganizationNewsDO> organizationNewsDOS = organizationNewsService.selectList(orWrapper);
            String str = "";
            for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS) {
                str = str + organizationNewsDO.getId() + ",";
            }
            wrapper.and();
            if (StringUtils.isNotBlank(str)) {
                wrapper.in("orgId", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("orgId", null);
            }
        }

        Page<UserDO> page = userService.selectPage(getPage(UserDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            UserDO obj = (UserDO) page.getRecords().get(i);
            if (obj.getOrgId() != null) {
                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
                if (organizationNewsDO != null) {
                    obj.setOrgName(organizationNewsDO.getName());
                }
            }
            if(obj.getUserRelevancyId() != null){
                SysUserRelevancyDO sysUserRelevancyDO  = userRelevancyService.selectById(obj.getUserRelevancyId());
                if(sysUserRelevancyDO!=null){
                    obj.setTrack(sysUserRelevancyDO.getTrack());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @Log("查询系统用户列表")
    @GetMapping("/marketUserList")
    @ResponseBody
    public Result<?> marketUserList() {
        Map map = new HashMap<String,Object>();
        map.put("name","市场部");
        List<Map> mapList = new ArrayList<Map>();
        Map map1 = new HashMap<String,Object>();
        map1.put("name","市场一部");
        Map map2 = new HashMap<String,Object>();
        map2.put("name","市场二部");
        Long roleId1=1386577149715402754L;//市场一部角色ID,直接写死id,提高效率
        Long roleId2=1386577245253259266L;//市场二部角色ID
        List<UserRoleDO> userRoleDOS1 = userRoleService.findByKv("roleId",roleId1);
        List<UserRoleDO> userRoleDOS2 = userRoleService.findByKv("roleId",roleId2);
        List<UserDO> userDOS1 = new ArrayList<UserDO>();
        List<UserDO> userDOS2= new ArrayList<UserDO>();
        List<Map> userMapList1 = new ArrayList<Map>();
        List<Map> userMapList2 = new ArrayList<Map>();
        for(UserRoleDO userRoleDO : userRoleDOS1){
            Map userMap = new HashMap<String,String>();
            userMap.put("name",userService.selectById(userRoleDO.getUserId()).getName());
            userMapList1.add(userMap);
        }
        for(UserRoleDO userRoleDO : userRoleDOS2){
            Map userMap = new HashMap<String,String>();
            userMap.put("name",userService.selectById(userRoleDO.getUserId()).getName());
            userMapList2.add(userMap);
        }
        map1.put("children",userMapList1);
        map2.put("children",userMapList2);
        mapList.add(map1);
        mapList.add(map2);
        map.put("children",mapList);
        return Result.ok(map);
    }


    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        List<RoleDO> roles = roleService.selectList(null);
        model.addAttribute("roles", roles);
        model.addAttribute("organizationNews", organizationNewsService.selByOrgId());
        return prefix + "/add";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        UserDO userDO = userService.selectById(id);
        model.addAttribute("user", userDO);
        List<RoleDO> roles = roleService.findListStatusByUserId(id);
        model.addAttribute("roles", roles);
        Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().orderBy("name");
        model.addAttribute("organizationNews", organizationNewsService.selectList(orWrapper));
        return prefix + "/edit";
    }

    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:user:user")
    String info(@PathVariable("id") Long id, Model model) {
        UserDO userDO = userService.selectById(id);
        model.addAttribute("user", userDO);
        return prefix + "/info";
    }

    @RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    Result<String> save(UserDO user) {
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
        if(organizationNewsDO != null){
            user.setOrgName(organizationNewsDO.getName());
        }
        user.setState(3);

        //获取用户子表相关属性
        SysUserRelevancyDO userRelevancyDO = new SysUserRelevancyDO();
       // userRelevancyDO.setTimeOfEnrollment(user.getTimeOfEnrollment());
        userRelevancyDO.setType(user.getUserType());
        userRelevancyDO.setTrack(user.getTrack());
        //添加用户扩展
        userRelevancyService.insert(userRelevancyDO);
        user.setUserRelevancyId(userRelevancyDO.getId());
        userService.insert(user);
        //userRelevancyDO.setSchool(user.getSchool());
       // userRelevancyDO.setSchoolAddress(user.getSchoolAddress());
       // userRelevancyDO.setSchoolIndetailAddress(user.getSchoolIndetailAddress());
       // userRelevancyDO.setSchoolLevel(user.getSchoolLevel());
      //  userRelevancyDO.setRatingCertificate(user.getRatingCertificate());
      //  userRelevancyDO.setDepartment(user.getDepartment());
      //  userRelevancyDO.setImg(user.getImg());
       // userRelevancyDO.setShippingAddress(user.getShippingAddress());
       // userRelevancyDO.setShippingIndetailAddress(user.getShippingIndetailAddress());
       // userRelevancyDO.setDutyParagraph(user.getDutyParagraph());
        //userRelevancyDO.setOrgName(user.getTicketOrgName());
       // userRelevancyDO.setCardNumber(user.getCardNumber());
       // userRelevancyDO.setAccountName(user.getAccountName());
       // userRelevancyDO.setBank(user.getBank());
      //  userRelevancyDO.setCreateTime(user.getCreateTime());
       // userRelevancyDO.setUpdateTime(user.getUpdateTime());

        return Result.ok();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    Result<String> update(UserDO user) {
//        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
//        if(organizationNewsDO != null){
//            user.setOrgName(organizationNewsDO.getName());
//        }else {
//            user.setOrgName(null);
//            user.setOrgId(null);
//            userService.updayeOrg(user);
//        }
        SysUserRelevancyDO userRelevancyDO = new SysUserRelevancyDO();
        userService.updateById(user);
        //更新用户扩展表
/*        userRelevancyDO.setId(user.getUserRelevancyId());
        userRelevancyDO.setTrack(user.getTrack());
        userRelevancyService.updateById(userRelevancyDO);*/
        return Result.ok();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    Result<String> updatePeronal(UserDO user) {
        userService.updatePersonal(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    @Transactional
    Result<String> remove(Long id) {
        boolean b = userService.deleteById(id);
        if(b){
            List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id",id);
            if(expertsDOS != null && expertsDOS.size() > 0){
                List<Long> ids = new ArrayList<>();
                for(ExpertsDO expertsDO : expertsDOS){
                    ids.add(expertsDO.getId());
                }
                boolean cc = expertsService.deleteBatchIds(ids);
                if(cc){
                    return Result.ok();
                }else{
                    return Result.fail();
                }
            }
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    @RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    @Transactional
    Result<String> batchRemove(@RequestParam("ids[]") Long[] userIds) {
        boolean b = userService.deleteBatchIds(Arrays.asList(userIds));
        if(b){
            boolean ccd = true;
            for(Long id : userIds){
                List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id",id);
                if(expertsDOS != null && expertsDOS.size() > 0){
                    List<Long> ids = new ArrayList<>();
                    for(ExpertsDO expertsDO : expertsDOS){
                        ids.add(expertsDO.getId());
                    }
                    ccd = expertsService.deleteBatchIds(ids);
                }
            }
            if(ccd){
                return Result.ok();
            }else{
                return Result.fail();
            }
        }else{
            return Result.fail();
        }
    }

    @PostMapping("/exist")
    @ResponseBody
    boolean exist(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exist(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    Result<String> resetPwd(UserVO userVO) {
        userService.resetPwd(userVO, getUser());
        return Result.ok();
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    Result<String> adminResetPwd(UserVO userVO) {
        userService.adminResetPwd(userVO);
        return Result.ok();

    }

    @RequiresPermissions("sys:user:add")
    @Log("审核")
    @PostMapping("/review")
    @ResponseBody
    Result<String> check(@RequestParam("ids[]") Long[] ids,Integer state  ,String remark) {

        //查询字典:消息模板
        DictDO dic = null;
        String valStr = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (state == 2){
            dic = dictService.findOneByKv("type" , "check_no_pass");
            valStr = dic.getValue().replace("{value4}" , remark);
        }else{
            dic = dictService.findOneByKv("type" , "check_pass");
            valStr = dic.getValue();
        }
        valStr =  valStr.replace("{value1}" , "个人信息");
        valStr = valStr.replace("{value2}" , this.getUser().getUsername());
        valStr = valStr.replace("{value3}" , formatter.format(new Date()));

        for (Long id : ids){
            UserDO user = userService.selectById(id);
            user.setState(state);

            MsgDO msg = new MsgDO();
            if (state == 1){
                msg.setTitle("您的个人信息审核通过！");
                user.setRemark("");
            }else {
                msg.setTitle("您的个人信息审核未通过！");
                user.setRemark(remark);
            }
            msg.setContent(valStr);
            msg.setCreaterId(this.getUserId());
            msg.setCreaterDate(new Date());
            msg.setType(1);
            msg.setMsgType(0);
            msg.setUserId(id);
            msg.setState(0);
            if (userService.updateById(user)){
                msgService.insert(msg);

                //------------------------订阅消息模块-----------------------------\
                MsgTemplateDO msgTemplate = msgTemplateService.findOneByKv("type" , 0, "temp_ip" ,user.getLastEdit());
//                UserDO user = userService.selectById(expertsDO.getUserId());
                if (user.getCerOpenId() != null || user.getTraOpenId() != null){
                    if (msgTemplate != null){
                        String[] value = null;
                        if (state == 1){//通过
                            MsgTemplateDO templateDO = msgTemplateService.findOneByKv("pid" , msgTemplate.getId() , "type" , 2, "temp_ip" ,user.getLastEdit());
                            value = templateDO.getContent().split("/n");
                            for (int a = 0; a < value.length; a++){
                                value[a] = value[a].replace("{value1}" ,"个人信息");
                                value[a] = value[a].replace("{value2}" ,"个人信息");
                                value[a] = value[a].replace("{date}" , formatter.format(new Date()));
                            }
                        }else if (state == 2){//未通过
                            MsgTemplateDO templateDO = msgTemplateService.findOneByKv("pid" , msgTemplate.getId() , "type" , 3 ,"temp_ip" ,user.getLastEdit());
                            value = templateDO.getContent().split("/n");
                            for (int a = 0; a < value.length; a++){
                                value[a] = value[a].replace("{value1}" ,"个人信息");
                                value[a] = value[a].replace("{value2}" ,"个人信息");
                                value[a] = value[a].replace("{remark}" ,remark);
                                value[a] = value[a].replace("{date}" , formatter.format(new Date()));
                            }
                        }
                        String[] parm = msgTemplate.getContent().split(",");
                        Map<String, TemplateData> map = PackTemplateMap.get1(value , parm);

                        MpConfigDO mc = mpConfigService.selectById(user.getLastEdit());
                        if (user.getLastEdit() == 101){
                            wxPushServiceQcl.sendMsgToUser(mc.getId().intValue() ,user.getCerOpenId(),msgTemplate.getCode(),map ,"pages/userInfo/userInfo");
                        }else {
                            wxPushServiceQcl.sendMsgToUser(mc.getId().intValue() ,user.getTraOpenId(),msgTemplate.getCode(),map ,"pages/userInfo/userInfo");
                        }


                    }
                }
                //------------------------订阅消息模块结束-----------------------------\

            }

        }
        return Result.ok();
    }


    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }

    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.selectById(getUserId());
        model.addAttribute("user", userDO);
        List<DictDO> hobbyList = dictService.getHobbyList(userDO);
        model.addAttribute("hobbyList", hobbyList);
        List<DictDO> sexList = dictService.getSexList();
        model.addAttribute("sexList", sexList);
        return prefix + "/personal";
    }

    @GetMapping("/adminMessage")
    String adminMessage(Model model, String state) {
        model.addAttribute("state", state);
        return prefix + "/adminMessage";
    }

    @Log("上传头像")
    @ResponseBody
    @PostMapping("/uploadImg")
    Result<?> uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request)
            throws Exception {
        Map<String, Object> result = new HashMap<>();
        result = userService.updatePersonalImg(file, avatar_data, getUserId());
        return Result.ok(result);
    }


    @Log("消息中心列表")
    @GetMapping("/msgList")
    @ResponseBody
    Result<?> msgList(int current, int number, String state, String type) {
        UserDO user = this.getUser();
        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("state", state);
        map.put("type", type);
        Page<MsgDO> page = msgService.selMsgPage(current, number, map);
        List<MsgDO> list = page.getRecords();
        for (MsgDO msg : list) {
            msg.setUserName(user.getUsername());
            UserDO user1 = userService.selectById(msg.getCreaterId());
            msg.setCreaterName(user1.getUsername());
        }
        page.setRecords(list);
        return Result.ok(page);
    }


    @Log("消息中心更改状态")
    @GetMapping("/updateState")
    @ResponseBody
    Result<?> updateState(Long id) {
        MsgDO msg = msgService.selectById(id);
        msg.setState(2);
        msgService.updateById(msg);
        return Result.ok();
    }


    @Log("未读消息条数")
    @GetMapping("/unreadNum")
    @ResponseBody
    Result<?> unreadNum(String type) {
        if (getUser() != null) {
            List<MsgDO> msg = msgService.findByKv("state", 0, "userId", this.getUserId(), "type", type);
            return Result.ok(msg.size());
        } else {
            return Result.ok(0);
        }

    }
}
